package pattern.template;

/**
 * 冒泡排序
 *
 * @author sun.ye
 * @since 2020-07-15 14:27
 */
public class BubbleSorter {

    static int operation;

    public static int sort(int[] array){
        operation = 0;
        if (array.length <= 1) {
            return operation;
        }
        for (int nextToLast = array.length - 2 ; nextToLast >= 0 ; nextToLast--){
            for (int i = 0; i < nextToLast; i++) {
                compareAndSwap(array,i);
            }
        }
        return operation;
    }

    private static void swap(int[] array, int index){
        int temp = array[index];
        array[index] = array[index+1];
        array[index + 1] = temp;
    }

    private static void compareAndSwap(int[] array,int index){
        if (array[index] > array[index + 1]){
            swap(array, index);
        }
        operation++;
    }


}